package com.hp.guard.biz;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;

import com.hp.guard.R;
import com.hp.guard.bean.UpdateBean;
import com.hp.guard.utils.Utils;
import com.hp.guard.utils.XmlParser;

public class LoginHelper {
	private static LoginHelper loginHelper;
	private Activity activity;
	private LoginTask mLoginTask;
	private AlertDialog  dialog;
	public LoginHelper(Activity activity) {
		this.activity=activity;
		mLoginTask=new LoginTask();
		mLoginTask.execute();
	}
	public static LoginHelper getInstance(Activity activity) {
		// TODO Auto-generated method stub
		loginHelper=new LoginHelper(activity);
		
		return loginHelper;
	}
	
	private class LoginTask extends	AsyncTask<Void, Void, UpdateBean>{
		@Override
		protected UpdateBean doInBackground(Void... params) {
			// TODO Auto-generated method stub
		UpdateBean bean=connect();
			return bean;
		}
		@Override
		protected void onPostExecute(UpdateBean bean) {
			// TODO Auto-generated method stub
			if(bean!=null){
				if(!bean.getVersion().equals(Utils.getVersion(activity))){
					dialog=new Builder(activity)
					.setTitle("提醒")
					.setMessage(bean.getDescription())
					.setPositiveButton("升级", new OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub	
						}
					})
					.setNegativeButton("取消", new OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.dismiss();
						}
					}).create();
					dialog.setCanceledOnTouchOutside(false);
					dialog.show();
					
				}else{
					
					enter();
				}
			}
		}
		
	}
	
	public UpdateBean connect() {
		// TODO Auto-generated method stub
		
		UpdateBean bean=null;
		try {
			String serverUrl=activity.getResources().getString(R.string.server_url);
			URL url=new URL(serverUrl+"info.xml");
			HttpURLConnection connection=(HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.setReadTimeout(5000);
			if(connection.getResponseCode()==200){
				InputStream inputStream=connection.getInputStream();
				bean=XmlParser.getUpdateBean(inputStream);
				
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bean;
	}
	public void enter() {
		// TODO Auto-generated method stub
		
	}
	


}
